
import request from '@/utils/services/axios'
import qs from 'qs'
import store from '@/store'
import { getStore, setStore } from '@/utils/util/store.js'
import { validatenull } from '@/utils/util/validate'
import website from '@/const/website.js'

const scope = 'server'

const sessionType = undefined // 设置为 undefined 则使用 localStorage, 使用 'session' 使用 sessionStorage，sessionStorage不能跨标签页，打开新标签页则需要重新登录，可以实现每个tab页不同用户登录

export const loginByUsername = (username, password, code, randomStr) => {
    const grant_type = 'password'
    const dataObj = qs.stringify({ username: username, password: password })
    const basicAuth = 'Basic ' + window.btoa(website.formLoginClient)

    // 保存当前选中的 basic 认证信息
    setStore({
        name: 'basicAuth',
        content: basicAuth,
        type: sessionType
    })

    return request({
        url: '/api/auth/oauth2/token',
        headers: {
            isToken: false,
            'TENANT-ID': '1',
            Authorization: basicAuth
        },
        method: 'post',
        params: { randomStr, code, grant_type, scope },
        data: dataObj
    })
}

export const refreshToken = (refresh_token) => {
    const grant_type = 'refresh_token'
    // 获取当前选中的 basic 认证信息
    const basicAuth = getStore({ name: 'basicAuth' })

    return request({
        url: '/api/auth/oauth2/token',
        headers: {
            isToken: false,
            'TENANT-ID': '1',
            Authorization: basicAuth
        },
        method: 'post',
        params: { refresh_token, grant_type, scope }
    })
}

export const loginByMobile = (mobile, code) => {
    const grant_type = 'mobile'
    const basicAuth = 'Basic ' + window.btoa(website.smsLoginClient)

    // 保存当前选中的 basic 认证信息
    setStore({
        name: 'basicAuth',
        content: basicAuth,
        type: sessionType
    })

    return request({
        url: '/api/auth/oauth2/token',
        headers: {
            isToken: false,
            'TENANT-ID': '1',
            Authorization: basicAuth
        },
        method: 'post',
        params: { mobile: 'SMS@' + mobile, code: code, grant_type, scope }
    })
}

export const loginBySocial = (state, code) => {
    const grant_type = 'mobile'
    const basicAuth = 'Basic ' + window.btoa(website.socialLoginClient)

    // 保存当前选中的 basic 认证信息
    setStore({
        name: 'basicAuth',
        content: basicAuth,
        type: sessionType
    })

    return request({
        url: '/api/auth/oauth2/token',
        headers: {
            isToken: false,
            'TENANT-ID': '1',
            Authorization: basicAuth
        },
        method: 'post',
        params: { mobile: state + '@' + code, code: code, grant_type, scope }
    })
}
export const loginByZj3Portal = (code) => {
    const grant_type = 'mobile'
    const basicAuth = 'Basic ' + window.btoa(website.zj3PortalLoginClient)

    // 保存当前选中的 basic 认证信息
    setStore({
        name: 'basicAuth',
        content: basicAuth,
        type: sessionType
    })

    return request({
        url: '/api/auth/oauth2/token',
        headers: {
            isToken: false,
            'TENANT-ID': '1',
            Authorization: basicAuth
        },
        method: 'post',
        params: { mobile: 'Zj3PortalLogin@' + code, code: code, grant_type, scope }
    })
}
export const loginByXindunCode = (code) => {
    const grant_type = 'mobile'
    const basicAuth = 'Basic ' + window.btoa(website.zj3PortalLoginClient)

    // 保存当前选中的 basic 认证信息
    setStore({
        name: 'basicAuth',
        content: basicAuth,
        type: sessionType
    })

    return request({
        url: '/api/auth/oauth2/token',
        headers: {
            isToken: false,
            'TENANT-ID': '1',
            Authorization: basicAuth
        },
        method: 'post',
        params: { mobile: 'Zj3UserCodeLogin@' + code, code: code, grant_type, scope }
    })
}
export const getUserInfo = () => {
    return request({
        url: '/api/admin/user/info',
        method: 'get'
    })
}

export const logout = () => {
    return request({
        url: '/api/auth/token/logout',
        method: 'delete'
    })
}

/**
 * 校验令牌，若有效期小于半小时自动续期
 * @param refreshLock
 */
export const checkToken = (refreshTime, refreshLock, $store) => {
    const token = store.getters.access_token
    // 获取当前选中的 basic 认证信息
    const basicAuth = getStore({ name: 'basicAuth' })

    request({
        url: '/api/auth/token/check_token',
        headers: {
            isToken: false,
            Authorization: basicAuth
        },
        method: 'get',
        params: { token }
    })
        .then((response) => {
            if (validatenull(response)) {
                clearInterval(refreshTime)
                return
            }

            const expire = response && response.data && response.data.exp
            //小于半小时自动续约
            if (expire && expire <= 12 * 60 * 60 * 1000) {
                if (!refreshLock) {
                    refreshLock = true
                    $store.dispatch('RefreshToken').catch(() => {
                        clearInterval(refreshTime)
                    })
                    refreshLock = false
                }
            }
        })
        .catch((error) => {
            console.error(error)
        })
}

/**
 * 注册用户
 */
export const registerUser = (userInfo) => {
    return request({
        url: '/api/admin/register/user',
        method: 'post',
        data: userInfo
    })
}

export const switchPost = (userId, username, defaultPostId) => {
    return request({
        url: '/api/admin/user/switchPost',
        method: 'post',
        params: { userId: userId, username: username, defaultPostId: defaultPostId }
    })
}

